<template>
  <div class="college-container">
    <!-- 顶部信息 -->
    <div class="college-header">
      <div class="college-info">
        <h1>{{ collegeInfo.name }}</h1>
        <p>{{ collegeInfo.description }}</p>
      </div>
      <div class="back-btn" @click="$router.go(-1)">
        <span class="icon">←</span> 返回
      </div>
    </div>

    <!-- 年级班级列表 -->
    <div class="grades-section">
      <div class="section-header">
        <h2>班级信息</h2>
        <button class="add-btn" @click="showAddClassModal = true">
          <span class="icon">+</span> 添加班级
        </button>
      </div>
      <div class="grade-list">
        <div v-for="grade in grades" :key="grade.id" class="grade-section">
          <div class="grade-header">
            <h3>{{ grade.name }}</h3>
            <div class="grade-stats">
              <div class="stat">
                <span class="label">班级数</span>
                <span class="value">{{ grade.classes.length }}</span>
              </div>
              <div class="stat">
                <span class="label">总人数</span>
                <span class="value">{{ getTotalStudents(grade) }}</span>
              </div>
            </div>
          </div>
          <div class="class-grid">
            <div 
              v-for="class_ in grade.classes" 
              :key="class_.id" 
              class="class-card"
              @click="goToClass(class_.id)"
            >
              <div class="class-header">
                <div class="class-icon">👥</div>
                <div class="class-name">{{ class_.name }}</div>
              </div>
              <div class="class-stats">
                <div class="stat-row">
                  <span class="label">学生数</span>
                  <span class="value">{{ class_.studentCount }}</span>
                </div>
                <div class="stat-row">
                  <span class="label">班主任</span>
                  <span class="value">{{ class_.teacher }}</span>
                </div>
              </div>
              <div class="class-actions">
                <button class="action-btn view-btn" @click.stop="goToClass(class_.id)">查看详情</button>
                <button class="action-btn edit-btn" @click.stop="editClass(class_)">编辑</button>
                <button class="action-btn delete-btn" @click.stop="confirmDeleteClass(class_)">删除</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加班级对话框 -->
    <div v-if="showAddClassModal" class="modal-backdrop" @click="showAddClassModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>添加班级</h3>
          <span class="close-btn" @click="showAddClassModal = false">&times;</span>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="className">班级名称：</label>
            <input type="text" id="className" v-model="newClass.name" placeholder="请输入班级名称" />
          </div>
          
          <div class="form-group">
            <label for="gradeId">年级：</label>
            <select id="gradeId" v-model="newClass.grade_id" @change="updateGradeName">
              <option value="" disabled selected>请选择年级</option>
              <option value="2020">2020级</option>
              <option value="2021">2021级</option>
              <option value="2022">2022级</option>
              <option value="2023">2023级</option>
              <option value="2024">2024级</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="departmentId">所属系部：</label>
            <select id="departmentId" v-model="newClass.department_id">
              <option value="" disabled selected>请选择系部</option>
              <option v-for="dept in departments" :key="dept.id" :value="dept.id">
                {{ dept.name }}
              </option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="teacherId">班主任：</label>
            <select id="teacherId" v-model="newClass.teacher_id">
              <option value="" disabled selected>请选择班主任</option>
              <option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">
                {{ teacher.name }}
              </option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showAddClassModal = false">取消</button>
          <button class="confirm-btn" @click="addNewClass" :disabled="!canAddClass">确定</button>
        </div>
      </div>
    </div>

    <!-- 编辑班级对话框 -->
    <div v-if="showEditClassModal" class="modal-backdrop" @click="showEditClassModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>编辑班级</h3>
          <span class="close-btn" @click="showEditClassModal = false">&times;</span>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="editClassName">班级名称：</label>
            <input type="text" id="editClassName" v-model="editingClass.name" placeholder="请输入班级名称" />
          </div>
          
          <div class="form-group">
            <label for="editGradeId">年级：</label>
            <select id="editGradeId" v-model="editingClass.grade_id" @change="updateEditingGradeName">
              <option value="" disabled>请选择年级</option>
              <option value="2020">2020级</option>
              <option value="2021">2021级</option>
              <option value="2022">2022级</option>
              <option value="2023">2023级</option>
              <option value="2024">2024级</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="editDepartmentId">所属系部：</label>
            <select id="editDepartmentId" v-model="editingClass.department_id">
              <option value="" disabled>请选择系部</option>
              <option v-for="dept in departments" :key="dept.id" :value="dept.id">
                {{ dept.name }}
              </option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="editTeacherId">班主任：</label>
            <select id="editTeacherId" v-model="editingClass.teacher_id">
              <option value="" disabled>请选择班主任</option>
              <option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">
                {{ teacher.name }}
              </option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="editStatus">状态：</label>
            <select id="editStatus" v-model="editingClass.status">
              <option :value="1">正常</option>
              <option :value="0">停用</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showEditClassModal = false">取消</button>
          <button class="confirm-btn" @click="updateClass" :disabled="!canUpdateClass">保存</button>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-backdrop" @click="showDeleteConfirm = false">
      <div class="modal-content confirm-dialog" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <span class="close-btn" @click="showDeleteConfirm = false">&times;</span>
        </div>
        <div class="modal-body">
          <p>确定要删除班级 "{{ classToDelete?.name }}" 吗？</p>
          <p class="warning">此操作不可逆，删除后数据将无法恢复。</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showDeleteConfirm = false">取消</button>
          <button class="delete-confirm-btn" @click="deleteClass">确认删除</button>
        </div>
      </div>
    </div>

    <!-- 添加路由出口 -->
    <router-view></router-view>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// import { collegeAPI } from '@/api/admin/college' // 注释掉旧的导入
import { 
  getYzhCollegeDetail, 
  getYzhCollegeClasses, 
  getDepartments, 
  getTeacherList,
  addYzhClass,
  updateYzhClass,
  deleteYzhClass
} from '@/api/admin/yzhTeacher' // 导入API

const route = useRoute()
const router = useRouter()

const collegeInfo = ref({
  name: '加载中...',
  description: '加载中...'
})

const grades = ref([])
const departments = ref([])
const teachers = ref([])

// 对话框控制
const showAddClassModal = ref(false)
const showEditClassModal = ref(false)
const showDeleteConfirm = ref(false)

// 新班级和编辑班级数据
const newClass = ref({
  name: '',
  grade_id: '',
  grade_name: '',
  college_id: 0,
  department_id: '',
  teacher_id: ''
})

const editingClass = ref({
  id: null,
  name: '',
  grade_id: '',
  grade_name: '',
  college_id: 0,
  department_id: '',
  teacher_id: '',
  status: 1
})

const classToDelete = ref(null)

// 计算属性
const canAddClass = computed(() => {
  return newClass.value.name && 
         newClass.value.grade_id && 
         newClass.value.grade_name && 
         newClass.value.college_id
})

const canUpdateClass = computed(() => {
  return editingClass.value.name && 
         editingClass.value.grade_id && 
         editingClass.value.grade_name && 
         editingClass.value.college_id
})

// 更新grade_name方法
const updateGradeName = () => {
  newClass.value.grade_name = `${newClass.value.grade_id}级`
}

const updateEditingGradeName = () => {
  editingClass.value.grade_name = `${editingClass.value.grade_id}级`
}

const getTotalStudents = (grade) => {
  return grade.classes.reduce((total, class_) => total + class_.studentCount, 0)
}

const goToClass = (classId) => {
  const collegeId = route.params.id
  console.log('Navigating to (new path):', `/admin/college/${collegeId}/class/${classId}`)
  router.push(`/admin/college/${collegeId}/class/${classId}`)
}

// 编辑班级
const editClass = (class_) => {
  editingClass.value = {
    id: class_.id,
    name: class_.name,
    grade_id: class_.grade_id,
    grade_name: class_.grade_name || `${class_.grade_id}级`,
    college_id: class_.college_id || parseInt(route.params.id),
    department_id: class_.department_id || '',
    teacher_id: class_.teacherId || '',
    status: class_.status === undefined ? 1 : class_.status
  }
  showEditClassModal.value = true
}

// 确认删除班级
const confirmDeleteClass = (class_) => {
  classToDelete.value = class_
  showDeleteConfirm.value = true
}

// 添加班级方法
const addNewClass = async () => {
  try {
    // 设置学院ID为当前学院
    newClass.value.college_id = parseInt(route.params.id)
    
    const response = await addYzhClass(newClass.value)
    if (response && response.status === 'success') {
      alert('班级添加成功！')
      showAddClassModal.value = false
      
      // 重置表单
      newClass.value = {
        name: '',
        grade_id: '',
        grade_name: '',
        college_id: 0,
        department_id: '',
        teacher_id: ''
      }
      
      // 刷新班级列表
      await fetchCollegeData()
    } else {
      alert(`添加失败: ${response?.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('添加班级时出错:', error)
    alert(`添加班级失败: ${error.response?.data?.message || error.message || '未知错误'}`)
  }
}

// 更新班级方法
const updateClass = async () => {
  try {
    const classId = editingClass.value.id
    const response = await updateYzhClass(classId, editingClass.value)
    
    if (response && response.status === 'success') {
      alert('班级信息更新成功！')
      showEditClassModal.value = false
      
      // 刷新班级列表
      await fetchCollegeData()
    } else {
      alert(`更新失败: ${response?.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('更新班级时出错:', error)
    alert(`更新班级失败: ${error.response?.data?.message || error.message || '未知错误'}`)
  }
}

// 删除班级方法
const deleteClass = async () => {
  if (!classToDelete.value || !classToDelete.value.id) {
    alert('无法删除：班级ID缺失')
    showDeleteConfirm.value = false
    return
  }
  
  try {
    const classId = classToDelete.value.id
    const response = await deleteYzhClass(classId)
    
    if (response && response.status === 'success') {
      alert('班级已成功删除！')
      showDeleteConfirm.value = false
      
      // 刷新班级列表
      await fetchCollegeData()
    } else {
      alert(`删除失败: ${response?.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('删除班级时出错:', error)
    alert(`删除班级失败: ${error.response?.data?.message || error.message || '未知错误'}`)
  }
}

// 获取学院信息和班级数据
const fetchCollegeData = async () => {
  try {
    const collegeId = route.params.id
    console.log('College.vue: Fetching data for college ID (yzh):', collegeId)

    // 获取学院详情 (yzh_colleges)
    const collegeRes = await getYzhCollegeDetail(collegeId)
    console.log('College.vue: yzh_college detail response:', collegeRes)
    if (collegeRes && collegeRes.status === 'success' && collegeRes.data) {
      collegeInfo.value = collegeRes.data // 假设后端直接返回学院对象在 data 属性
    } else {
      collegeInfo.value = { name: '学院信息加载失败', description: '请检查API或网络' }
      console.error('College.vue: 获取 yzh_college 详情失败:', collegeRes)
    }

    // 获取学院班级数据 (yzh_classes)
    const classesRes = await getYzhCollegeClasses(collegeId)
    console.log('College.vue: yzh_college classes response:', classesRes)
    if (classesRes && classesRes.status === 'success' && classesRes.data && classesRes.data.classes) {
      // ... (existing logic to process classesRes.data.classes into grades.value)
      // Make sure the processing logic matches the new API response structure for yzh_classes
      const gradeMap = {}
      classesRes.data.classes.forEach(cls => {
        const gradeId = cls.grade_id || 'defaultGrade' // Adjust if grade_id field name is different in yzh_classes
        const gradeName = cls.grade_name || `年级 ${gradeId}` // Adjust for grade_name
          if (!gradeMap[gradeId]) {
            gradeMap[gradeId] = {
              id: gradeId,
            name: gradeName,
              classes: []
            }
          }
          gradeMap[gradeId].classes.push({
            id: cls.id,
            name: cls.name,
            studentCount: cls.student_count || 0, // Adjust for student_count
            teacher: cls.teacher_name || 'N/A', // Adjust for teacher_name
            grade_id: cls.grade_id,
            grade_name: cls.grade_name,
            department_id: cls.department_id,
            teacherId: cls.teacher_id,
            status: cls.status
          })
        })
      grades.value = Object.values(gradeMap).sort((a, b) => (b.name.localeCompare(a.name)));

      } else {
      console.error('College.vue: 获取 yzh_college 班级列表失败或格式不正确:', classesRes)
      // Fallback to static data if API fails or data is not as expected
      // ... (existing static data fallback for grades)
    }

    // 获取系部列表
    const departmentsRes = await getDepartments(collegeId);
    console.log('College.vue: yzh_college departments response:', departmentsRes);
    if (departmentsRes && departmentsRes.status === 'success' && departmentsRes.data && departmentsRes.data.departments) {
      departments.value = departmentsRes.data.departments;
    }
    
    // 获取教师列表
    const teachersRes = await getTeacherList({ college_id: collegeId });
    console.log('College.vue: teachers response:', teachersRes);
    if (teachersRes && teachersRes.status === 'success' && teachersRes.data && teachersRes.data.teachers) {
      teachers.value = teachersRes.data.teachers;
    }

  } catch (error) {
    console.error('College.vue: 获取学院综合数据失败 (yzh):', error)
    // ... (existing error handling and static data fallback)
  }
}

onMounted(() => {
  console.log('College ID:', route.params.id)
  fetchCollegeData()
})
</script>

<style scoped>
.college-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 30px;
}

.college-header {
  background: white;
  border-radius: 16px;
  padding: 30px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.college-info h1 {
  font-size: 32px;
  color: #333;
  margin-bottom: 12px;
}

.college-info p {
  color: #666;
  font-size: 16px;
  max-width: 600px;
  line-height: 1.6;
}

.back-btn {
  padding: 10px 20px;
  background: #f0f2f5;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #333;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: #e6e8eb;
  transform: translateX(-2px);
}

.grades-section {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.section-header h2 {
  font-size: 24px;
  color: #333;
}

.add-btn {
  padding: 10px 20px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.add-btn:hover {
  background: #40a9ff;
  transform: translateY(-2px);
}

.grade-section {
  margin-bottom: 30px;
}

.grade-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.grade-header h3 {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.grade-stats {
  display: flex;
  gap: 20px;
}

.grade-stats .stat {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.grade-stats .label {
  font-size: 14px;
  color: #999;
  margin-bottom: 4px;
}

.grade-stats .value {
  font-size: 18px;
  color: #333;
  font-weight: bold;
}

.class-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.class-card {
  background: #f9fafc;
  border-radius: 10px;
  padding: 20px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.class-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.class-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.class-icon {
  width: 40px;
  height: 40px;
  background: #e6f7ff;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.class-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.class-stats {
  border-top: 1px dashed #eaeaea;
  padding-top: 15px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-row .label {
  color: #999;
  font-size: 14px;
}

.stat-row .value {
  color: #333;
  font-weight: 500;
}

.class-actions {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.action-btn {
  flex: 1;
  padding: 8px 0;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.view-btn {
  background-color: #1890ff;
  color: white;
}

.view-btn:hover {
  background-color: #40a9ff;
}

.edit-btn {
  background-color: #52c41a;
  color: white;
}

.edit-btn:hover {
  background-color: #73d13d;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.delete-btn:hover {
  background-color: #ff7875;
}

/* 模态框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(2px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.confirm-dialog {
  max-width: 400px;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eaeaea;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.cancel-btn, .confirm-btn, .delete-confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 15px;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f1f1f1;
  color: #666;
}

.cancel-btn:hover {
  background: #e0e0e0;
}

.confirm-btn {
  background: #1890ff;
  color: white;
}

.confirm-btn:hover {
  background: #40a9ff;
}

.confirm-btn:disabled {
  background: #b3d9ff;
  cursor: not-allowed;
}

.delete-confirm-btn {
  background: #ff4d4f;
  color: white;
}

.delete-confirm-btn:hover {
  background: #ff7875;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input, .form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  font-size: 15px;
  transition: border-color 0.3s;
}

.form-group input:focus, .form-group select:focus {
  outline: none;
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.warning {
  color: #ff4d4f;
  font-weight: 500;
}
</style> 